<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="店铺编码" prop="storeCode">
        <el-input
          v-model="queryParams.storeCode"
          placeholder="请输入店铺编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户号" prop="subMchNo">
        <el-input
          v-model="queryParams.subMchNo"
          placeholder="请输入商户号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="订单支付流水号" prop="payOrderSerial" label-width="120">
        <el-input
          v-model="queryParams.payOrderSerial"
          placeholder="请输入订单支付流水号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="清算状态" prop="liquidationStatus">
        <el-select v-model="queryParams.liquidationStatus" placeholder="请选择清算状态" clearable size="small" style="width:180px"
                   @keyup.enter.native="handleQuery">
          <el-option v-for="item in liquidationStatusTag" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="dateRange" size="small" style="width: 240px" value-format="yyyy-MM-dd"
                        type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['store:liquidation:import']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['store:liquidation:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="liquidationList" @selection-change="handleSelectionChange">
      <el-table-column label="清算编号" align="center" prop="liquidationId"/>
      <el-table-column label="店铺编码" align="center" prop="storeCode"/>
      <el-table-column label="商户号" align="center" prop="subMchNo"/>
      <el-table-column label="清算角色" align="left" prop="liquidationRole">
        <template slot-scope="scope">
          <el-tag size="medium">
            <dict-tag :options="dict.type.radit_role" :value="scope.row.liquidationRole" />
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="分账金额" align="center" prop="liquidationAmount" />
      <el-table-column label="平台补贴" align="center" prop="orderCouponAmount" />
      <el-table-column label="订单实付金额" align="center" prop="couponAmount" />
      <el-table-column label="合计金额" align="center" prop="totalAmount" />
      <el-table-column label="退款金额" align="center" prop="refundAmount" />
      <el-table-column label="订单支付流水号" align="center" prop="payOrderSerial" />
      <el-table-column label="清算状态" align="center" prop="liquidationStatus">
        <template v-slot="scope">
          <dic-staus-tag :options="liquidationStatusTag" :staus="scope.row.liquidationStatus"></dic-staus-tag>
        </template>
      </el-table-column>
      <el-table-column label="店铺名称" align="center" prop="storeName" />
      <el-table-column label="分账比例" align="center" prop="proportion" />
      <el-table-column label="对公账户" align="center" prop="corporateAccount" />
<!--      <el-table-column label="开户行" align="center" prop="openBank" />-->
      <el-table-column label="支行联号" align="center" prop="branchNumb" />
      <el-table-column label="银行名称" align="center" prop="bankName" />
      <el-table-column label="法人手机号" align="center" prop="personPhone" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改订单清算对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="店铺编码" prop="storeCode">
          <el-input v-model="form.storeCode" placeholder="请输入店铺编码" />
        </el-form-item>
        <el-form-item label="商户号" prop="subMchNo">
          <el-input v-model="form.subMchNo" placeholder="请输入商户号" />
        </el-form-item>
        <el-form-item label="分账金额" prop="liquidationAmount">
          <el-input v-model="form.liquidationAmount" placeholder="请输入分账金额" />
        </el-form-item>
        <el-form-item label="订单支付流水号" prop="payOrderSerial">
          <el-input v-model="form.payOrderSerial" placeholder="请输入订单支付流水号" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    addLiquidation,
    delLiquidation,
    getLiquidation,
    listLiquidation,
    updateLiquidation
  } from "@/api/store/liquidation";
  import { getToken } from "@/utils/auth";

  export default {
  name: "Liquidation",
    dicts: ['radit_role'],
  data() {
    return {
      liquidationStatusTag: [
        { value: 0, label: "未清算", cssClass: "danger" },
        { value: 1, label: "已清算", cssClass: "success" },
        { value: 2, label: "清算失败", cssClass: "error" }
      ],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单清算表格数据
      liquidationList: [],
      // 日期范围
      dateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeCode: undefined,
        subMchNo: undefined,
        liquidationAmount: undefined,
        payOrderSerial: undefined,
        liquidationStatus: undefined,
      },
      // 清算导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/store/liquidation/importData"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询订单清算列表 */
    getList() {
      this.loading = true;
      listLiquidation(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.liquidationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        liquidationId: undefined,
        storeCode: undefined,
        subMchNo: undefined,
        liquidationAmount: undefined,
        payOrderSerial: undefined,
        liquidationStatus: 0,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "清算数据导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      console.log(response)
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      let msg = "导入成功";
      if(response.code !== 200){
          msg = "导入失败";
      }
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('store/liquidation/importTemplate', {
      }, `liquidation_template_${new Date().getTime()}.xlsx`)
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.liquidationId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加订单清算";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const liquidationId = row.liquidationId || this.ids
      getLiquidation(liquidationId).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改订单清算";
      });
    },
    addDateRange(params, dateRange) {
      let search = params;
      dateRange = Array.isArray(dateRange) ? dateRange : [];
      search['startDate'] = dateRange[0];
      search['endDate'] = dateRange[1];
      return search;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.liquidationId != null) {
            updateLiquidation(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addLiquidation(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const liquidationIds = row.liquidationId || this.ids;
      this.$modal.confirm('是否确认删除订单清算编号为"' + liquidationIds + '"的数据项？').then(() => {
        this.loading = true;
        return delLiquidation(liquidationIds);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('store/liquidation/export', {
        ...this.queryParams
      }, `liquidation_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
